<template>
  <a-layout style="min-height: 100vh;">
    <a-layout-content style="padding: 24px;">
      <div style="max-width: 1200px; margin: 0 auto;">
        <a-tabs v-model:activeKey="activeTab" size="large">
          <a-tab-pane key="questions">
            <template #tab><BookOutlined /> 题目收藏</template>
            <!-- 题目收藏内容 -->
            <a-space direction="vertical" style="width: 100%;" size="large">
              <a-row justify="space-between" align="middle">
                <a-col>
                  <a-space>
                    <a-button type="primary" @click="showNewFolderModal">
                      <template #icon><FolderAddOutlined /></template>
                      新建收藏夹
                    </a-button>
                    <a-button type="primary" @click="questionByAi">
                      <template #icon><CodeSandboxOutlined /></template>
                      AI生成题目
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
              <div>
                <a-space wrap>
                  <a-tag :color="selectedFolder === 'all' ? 'blue' : 'default'" @click="selectedFolder = 'all'" style="cursor: pointer; padding: 4px 12px;">
                    <FolderOpenOutlined />
                    全部题目
                  </a-tag>
                  <a-tag v-for="folder in collects" :key="folder.id" 
                  :color="selectedFolder === folder.id ? 'blue' : 'default'" 
                  style="cursor: pointer; padding: 4px 12px;" closable 
                  @click="selectedFolder = folder.id" 
                  @close="(e) => deleteFolderRe(e, folder.id)">
                    <FolderOutlined />
                    {{ folder.typeName }}
                  </a-tag>
                </a-space>
              </div>
                
              <a-row>
                <a-col :span="8">
                  <a-input v-model:value="questionSearchText" placeholder="搜索题目..." allow-clear>
                    <template #prefix><SearchOutlined /></template>
                  </a-input>
                </a-col>
              </a-row>

              <a-table 
              v-if="!loading.collects && collects.length > 0"
              :columns="questionColumns" 
              :data-source="filteredQuestions" 
              :pagination="{ pageSize: 10 }" row-key="id">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'content'">
                    <div>
                      <div style="font-weight: 500; margin-bottom: 4px;">{{ record.title }}</div>
                      <a-tag size="small" color="geekblue">{{ record.category }}</a-tag>
                    </div>
                  </template>
                  <template v-if="column.key === 'difficulty'">
                    <a-space>
                      <a-rate :value="record.difficulty" :count="5" disabled style="font-size: 14px;" />
                      
                    </a-space>
                  </template>
                  <template v-if="column.key === 'actions'">
                    <a-space>
                      <a-button 
                      type="link" 
                      size="small"
                      @click="handleView(record)"
                      ><EyeOutlined /> 查看</a-button>
                      <a-button 
                      type="link" 
                      size="small" 
                      danger
                      :disabled="selectedFolder === 'all'"
                      @click="handleUncollect(record.id, selectedFolder)"
                      ><DeleteOutlined /> 取消收藏</a-button>
                    </a-space>
                  </template>
                </template>
              </a-table>
            </a-space>
          </a-tab-pane>

          <a-tab-pane key="mistakes">
            <template #tab><ExclamationCircleOutlined /> 错题记录</template>
            <!-- 错题记录内容 -->
            <a-space direction="vertical" style="width: 100%;" size="large">
              <a-row>
                <a-col :span="8">
                  <a-input v-model:value="mistakeSearchText" placeholder="搜索错题..." allow-clear>
                    <template #prefix><SearchOutlined /></template>
                  </a-input>
                </a-col>

                <a-col :span="8" style="margin-left: 15px;">
                    <a-button type="primary" @click="mistakequestionByAi">
                      <template #icon><CodeSandboxOutlined /></template>
                      AI生成题目
                    </a-button>
                </a-col>
                
              </a-row>

              <a-row :gutter="[16, 16]">
                <a-col v-for="mistake in filteredMistakes" :key="mistake.id" :xs="24" :sm="12" :lg="8">
                  <a-card  size="small">
                     <template #title>
                          <div style="white-space: normal; word-break: break-word; margin: 8px 0; padding: 4px 8px; font-size: 16px; font-weight: 500;">
                            {{ mistake.parsedContent?.title || '题目' }}
                          </div>
                        </template>
                    <template #extra>
                      <a-space>
                        <!-- <EditOutlined style="cursor: pointer;" /> -->
                        <DeleteOutlined style="cursor: pointer; color: #ff4d4f;" 
                         @click="confirmDelete(mistake.mistakeId)"/>
                      </a-space>
                    </template>
                      
                    
                     <!-- 选项展示 -->
                        <div v-if="mistake.parsedContent?.options" class="question-options" style="margin-bottom: 12px;">
                          <div
                            v-for="(option, index) in mistake.parsedContent.options"
                            :key="index"
                            style="margin: 4px 0;"
                          >
                            {{ option }}
                          </div>
                        </div>
                    <a-collapse ghost>
                      <!-- <a-collapse-panel key="1" header="错误答案">
                        <div style="background: #fff2f0; padding: 12px; border-radius: 4px;">{{ mistake.wrongAnswer }}</div>
                      </a-collapse-panel> -->
                      <a-collapse-panel key="2" header="正确答案">
                              <div style="margin-bottom: 12px;">
                            <a-space>
                              <a-tag color="blue">{{ mistake.answer }}</a-tag>
                              <!-- <a-tag :color="getErrorTypeColor(mistake.errorType)">{{ mistake.errorType }}</a-tag> -->
                            </a-space>
                          </div>
                        <div style="background: #f6ffed; padding: 12px; border-radius: 4px;" v-html="mistake.analysis"></div>
                      </a-collapse-panel>
                    </a-collapse>

                    <div style="margin-top: 12px; text-align: right; color: #999; font-size: 12px;">
                      <CalendarOutlined />
                      {{ mistake.createTime }}
                    </div>
                  </a-card>
                </a-col>
              </a-row>
            </a-space>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-layout-content>
  </a-layout>

  <a-modal v-model:open="newFolderModalVisible" title="新建收藏夹" @ok="handleCreateFolder">
    <a-form :model="newFolderForm" layout="vertical">
      <a-form-item label="文件夹名称" required>
        <a-input v-model:value="newFolderForm.name" placeholder="请输入文件夹名称" @press-enter="handleCreateFolder" />
      </a-form-item>
    </a-form>
  </a-modal>

<!-- 文本详细弹窗 -->
<a-modal
  v-model:open="showDetailModal"
  title="题目信息"
  :footer="null"
  width="600"
>
    <div v-if="currentQuestion">
    <!-- 题目标题 -->
    <p><strong>标题：</strong> {{ currentQuestion.title }}</p>

    <!-- 难度 -->
    <p><strong>难度：</strong>
      <a-rate :value="currentQuestion.difficulty" disabled :count="5" />
      <span style="margin-left: 8px;">{{ currentQuestion.difficultyText }}</span>
    </p>

    <!-- 题干内容 -->
    <p><strong>题干：</strong></p>
    <div style="padding: 8px; background: #f6f6f6; border-radius: 4px;">
      {{ JSON.parse(currentQuestion.content).title }}
    </div>

    <!-- 选项 -->
    <p><strong>选项：</strong></p>
    <ul>
      <li v-for="(opt, index) in currentQuestion.options" :key="index">
        {{ opt }}
      </li>
    </ul>

    <!-- 正确答案 -->
    <p><strong>正确答案：</strong> {{ currentQuestion.answer }}</p>

    <!-- 解析 -->
    <p><strong>解析：</strong></p>
    <div style="padding: 10px; background: #f0f9eb; border-radius: 4px;">
      {{ currentQuestion.analysis || '暂无解析' }}
    </div>
  </div>

</a-modal>

</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  BookOutlined,
  ExclamationCircleOutlined,
  FolderAddOutlined,
  FolderOpenOutlined,
  FolderOutlined,
  SearchOutlined,
  EyeOutlined,
  DeleteOutlined,
  EditOutlined,
  CalendarOutlined,
  CodeSandboxOutlined
} from '@ant-design/icons-vue'
import {  Modal,message } from 'ant-design-vue'

import {addCollectFolder,deleteFolder,listByUserId1  } from '@/api/bizQuestionUserCollectionController'//用户收藏夹的操作
import{add1,addMulti,delete2,getQuestionsInCollect,} from '@/api/bizQuestionCollectionController' //操作收藏夹的问题的操作
import{add2,batchDelete,delete3,listByUserId,listMistakeQuestionsByUserId} from '@/api/bizQuestionMistakeController' //错题集当中错题的操作 
// 用户信息相关 - 直接在组件中实现


const activeTab = ref('questions')
const selectedFolder = ref('all')
const questionSearchText = ref('')
const mistakeSearchText = ref('')
const newFolderModalVisible = ref(false)
const newFolderForm = ref({ name: '' })

const folders = ref([ ])

const collects = ref([ ])

const mistakes = ref([
  {
  }
])

const questionColumns = [
  { title: '题目', key: 'content', dataIndex: 'content', width: '60%' },
  { title: '难度', key: 'difficulty', dataIndex: 'difficulty', width: '20%' },
  { title: '操作', key: 'actions', width: '20%' }
]

const filteredQuestions = computed(() => {
  let questions = []
  if (selectedFolder.value === 'all') {
    questions = collects.value.flatMap(folder => folder.questions || [])
  } else {
    const selected = collects.value.find(folder => folder.id === selectedFolder.value)
    questions = selected?.questions || []
  }
  if (!questionSearchText.value) return questions
  const keyword = questionSearchText.value.toLowerCase()
  return questions.filter(q => {
    const title = (q.title || '').toLowerCase()
    const options = (q.options || []).join(' ').toLowerCase()
    return title.includes(keyword) || options.includes(keyword)
  })
})

const filteredMistakes = computed(() => {
  if (!mistakeSearchText.value) return mistakes.value
  const keyword = mistakeSearchText.value.toLowerCase()
  return mistakes.value.filter(m => {
    const title = m.parsedContent?.title?.toLowerCase() || ''
    const options = m.parsedContent?.options?.join(' ').toLowerCase() || ''
    const analysis = m.analysis?.toLowerCase() || ''
    return title.includes(keyword) || options.includes(keyword) || analysis.includes(keyword)
  })
})

const showNewFolderModal = () => {
  newFolderModalVisible.value = true
  newFolderForm.value.name = ''
}

 const handleCreateFolder = () => {
  if (!newFolderForm.value.name.trim()) {
    message.error('请输入文件夹名称')
    return
  }
  folders.value.push({ id: Date.now(), name: newFolderForm.value.name.trim() })


  try {

    const res =  addCollectFolder({
      name: newFolderForm.value.name.trim()
    })
    fetchCollects()
  } catch (e) {
    message.error('请求异常')
    console.log("cuowuxinxi:"+e);
    
  }
  newFolderModalVisible.value = false
  message.success('文件夹创建成功')
}

const deleteFolderRe = (e,folderId) => {

 
  e.preventDefault()
  const folder = collects.value.find(f => f.id === folderId)
   console.log("shanchu"+folderId);
  console.log( folder);
  
  Modal.confirm({
    title: '确认删除该收藏夹？',
    content: `你将删除收藏夹「${folder.typeName}」，其中的题目仍会保留。确定继续吗？`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk() {
      console.log(`用户ID删除收藏夹: ${folder.typeName}`)
      deleteFolder({ id: folderId });
      fetchCollects()
      const index = collects.value.findIndex(f => f.id === folderId)
          if (index !== -1) {
            collects.value.splice(index, 1)
            
            if (selectedFolder.value === folderId) {
              selectedFolder.value = 'all'
            }
            message.success('收藏夹已删除')
          }
      fetchCollects();
    }
  })
}
const getErrorTypeColor = (errorType) => {
  const map = {
    '概念错误': 'red',
    '计算错误': 'orange',
    '方法错误': 'volcano',
    '理解错误': 'magenta'
  }
  return map[errorType] || 'default'
}
const loading = ref({ collects: false, mistakes: false })
// 获取收藏夹和题目列表
const fetchCollects = async () => {
  loading.value.collects = true
  try {
    const res = await listByUserId1()
    if (res.data.code === 0) {
      const folders = res.data.data
      for (const folder of folders) {
        // 初始化为空
        folder.questions = []

        // 获取该收藏夹的题目
        const qRes = await getQuestionsInCollect({ collectId: folder.id })
        const questions = qRes.data?.data || []

        // 解析每道题目的 content 字段
        for (const question of questions) {
          try {
            const parsedContent = JSON.parse(question.content)
            question.title = parsedContent.title || ''
            question.options = parsedContent.options || []
            //question.parentid = collectId
          } catch (err) {
            console.warn('解析题目 content 失败', question.content, err)
            question.title = ''
            question.options = []
          }
          
        }

        // 设置到 folder 中
        folder.questions = questions

        console.log("folder.questions2", folder.questions)
      }

      // 设置最终结果
      collects.value = folders
      console.log("folder.collect", collects.value)
    } else {
      message.error('获取收藏夹失败')
    }
  } catch (e) {
    message.error('请求收藏夹异常')
    console.log('e', e)
  } finally {
    loading.value.collects = false
  }
}

// 获取错题记录
const fetchMistakes = async () => {
  loading.value.mistakes = true
  try {
    const res = await listMistakeQuestionsByUserId()
    if (res.data.code === 0) {
      // 解析 content 字段，变成 parsedContent
      mistakes.value = res.data.data.map(item => {
        try {
          const parsed = JSON.parse(item.content)
          return {
            ...item,
            parsedContent: parsed // 增加一个新字段
          }
        } catch (e) {
          console.warn('解析 content 失败', item.content)
          return item // 保留原始内容
        }
      })
    } else {
      message.error('获取错题失败')
    }
  } catch (e) {
    message.error('请求错题异常')
  } finally {
    loading.value.mistakes = false
  }
  console.log("mistakes",mistakes.value);
  
}
// 渲染错题项
const renderMistakeItem = (item) =>
  h(
    'div',
    {
      style: { display: 'flex', justifyContent: 'space-between' }
    },
    [
      h('span', `题目ID: ${item.questionId}`),
      h(
        Popconfirm,
        {
          title: '确认移除该错题？',
          onConfirm: () => removeMistake(item.id)
        },
        {
          default: () =>
            h(
              'a',
              { style: 'color: red; margin-left: 10px; cursor: pointer' },
              '移除'
            )
        } 
      )
    ]
  )
const handleUncollect = async (questionId, folderId) => {
  console.log('题目 id 是：',questionId )
  console.log('收藏夹 id 是：', folderId)
  try {
    const res = await delete2({ questionId: questionId, collectId: folderId }) // 调用后端 API
    if (res.data.code === 0) {
      message.success('取消收藏成功')
      fetchCollects() // 重新拉取收藏夹及题目数据
    } else {
      message.error(res.data.msg || '取消收藏失败')
    }
  } catch (e) {
    console.error('取消收藏异常', e)
    message.error('取消收藏异常')
  }
}
//查看详细的题目详情
const showDetailModal = ref(false)
const currentQuestion = ref(null)

const handleView = (record) => {
  currentQuestion.value = record
  showDetailModal.value = true
}
//ai生成题目
import { useAiQuestionStore } from '@/stores/useAiQuestionStore'
import { useRouter } from 'vue-router'

const router = useRouter()
const aiQuestionStore = useAiQuestionStore()

const questionByAi = () => {
  const titles = filteredQuestions.value.map(q => q.title) // 当前文件夹的题目 title
  aiQuestionStore.setTitles(titles)
  router.push('/ai-generate') // 跳转页面
}
const mistakequestionByAi = () => {
 const titles = filteredMistakes.value.map(m => m.parsedContent?.title).filter(Boolean) // 当前文件夹的题目 title
  aiQuestionStore.setTitles(titles)
  router.push('/ai-generate') // 跳转页面
}
//错误题目的删除按钮逻辑
function confirmDelete(id) {
  console.log("删除的错误id",id);
  
  Modal.confirm({
    title: '确认删除',
    content: '是否确认删除该错题记录？',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        await delete3({ id })
        message.success('删除成功')
        fetchMistakes()
        // 删除成功后从本地移除该记录
        //filteredMistakes.value = filteredMistakes.value.filter(item => item.id !== id)
        mistakes.value = mistakes.value.filter(item => item.id !== id)
      } catch (err) {
        console.error('删除失败', err)
        message.error('删除失败')
      }
    }

  })
  
}
// 组件挂载时检查用户登录状态
onMounted(() => {
  fetchCollects()
  fetchMistakes()
})
</script>
